package io.karl.code_gen;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.model.ClassAnnotationAttributes;
import io.karl.code_gen.config.ConfigProperties;
import io.karl.code_gen.config.DataSourceConfig;
import io.karl.code_gen.config.PackageConfig;
import lombok.Data;

public class CodeGenerator {

    public static void generate(ConfigProperties config) {
        PackageConfig pc = config.getPackageName();
        DataSourceConfig dataSource = config.getDataSource().get(config.getUseDataSource());
        FastAutoGenerator.create(dataSource.getUrl(), dataSource.getUserName(), dataSource.getPassword())
                .globalConfig(builder -> builder
                        .author(config.getAuthor())
                        .outputDir(config.getOutputDir())
                        .disableOpenDir() // 禁止打开输出目录
                )
                .packageConfig(builder -> builder
                        .parent(pc.getParent())
                        .moduleName(pc.getModule())
                        .entity(pc.getEntity())
                        .mapper(pc.getMapper())
                        .xml(pc.getMapper() + ".xml")
                        .service(pc.getService())
                        .serviceImpl(pc.getService() + ".impl")
                )
                .strategyConfig(builder -> builder
                        .addInclude(config.getIncludeTables())
                        .entityBuilder()
                            .disableSerialVersionUID()
                            .logicDeleteColumnName(config.getDeleteColumn())
                            .enableLombok(new ClassAnnotationAttributes(Data.class))
                            .addTableFills(new Column("create_time", FieldFill.INSERT))
                            .addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE))
                            .addTableFills(new Column("deleted", FieldFill.INSERT))
                        .serviceBuilder()
                            .convertServiceFileName(entityName -> entityName + ConstVal.SERVICE)
                        .controllerBuilder()
                            .enableRestStyle()
                )
                .templateEngine(new VelocityTemplateEngine())
                .execute();
    }
}
